package com.adam.example;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.adam.example.types.Book;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;

import java.io.IOException;

public class ElasticsearchClientExample {

    public static void main(String[] args) throws IOException {
        // Authentication
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                "elastic", "elastic"));

        // Create the low-level client
        RestClient restClient = RestClient.builder(
                        new HttpHost("192.168.0.112", 9200))
                .setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder
                        .setDefaultCredentialsProvider(credentialsProvider))
                .build();

        // Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // And create the API client
        ElasticsearchClient client = new ElasticsearchClient(transport);

        SearchResponse<Book> searchResponse = client.search(searchRequestBuilder -> searchRequestBuilder
                        .index("test_books")
                        .query(queryBuilder -> queryBuilder
                                .term(termQueryBuilder -> termQueryBuilder
                                        .field("title")
                                        .value(valueBuilder -> valueBuilder.stringValue("java"))
                                )
                        )
                , Book.class);

        for(Hit<Book> hit: searchResponse.hits().hits()) {
            Book book = hit.source();
            System.out.println(book);
        }

        transport.close();
    }

}
